import { _decorator, AssetManager, Component, director, Node, SceneAsset } from 'cc'
import { Pipeline } from '../Base/Pipeline'
import ResourceManager from '../Runtime/ResourceManager'
import EventManager from '../Runtime/EventManager'
import { GAME_STATE_ENUM } from '../Config/Enums/EnumsIndex'
const { ccclass, property } = _decorator

@ccclass('LoginScene')
export class LoginScene extends Component {
  /** 登录流程管线 */
  private pipeline: Pipeline = null
  private createNewPipeline() {
    this.pipeline = new Pipeline()
    this.pipeline.target = this
    this.pipeline.finishCallback = err => {
      this.finishPipeline()
      if (err) {
      }
    }
  }
  private finishPipeline() {
    this.pipeline = null
  }

  onBtnStartClick() {
    /**登陆按钮 */
    ResourceManager.Instance.loadBundle('mainScene', (bundle: AssetManager.Bundle) => {
      bundle.loadScene(
        'MainScene',
        (finish: number, total: number, item: AssetManager.RequestItem) => {
          this.onProgress(finish / total)
        },
        (error: Error, sceneAsset: SceneAsset) => {
          // DYTools.log("主页场景资源加载完毕 ", new Date().getTime() - t, "ms");
          if (sceneAsset) {
            this.mainSceneAsset = sceneAsset
            this.switchToMain()
          } else {
            //erro
          }
        },
      )
    })
  }
  /** 主界面 */
  private mainSceneAsset: SceneAsset = null
  public switchToMain(): void {
    // 切换到主场景
    this.scheduleOnce(() => {
      director.runScene(this.mainSceneAsset)
    }, 0.5)
  }
  onProgress(percent) {
    // 单机模式，几种资源连续加载
    // const curStepSeconds: number = loadStepSeconds[this.loadAssetType] * percent // 当前步骤的时间
    const curStepSeconds: number = 40 * percent // 当前步骤的时间
    const progress = ((20 + curStepSeconds) / 2) * 100
    // cc.log(`loadAssetType:${LoadAssetType[this.loadAssetType]} loadedSeconds:${loadedSeconds} curStepSeconds:${curStepSeconds} totalSeconds:${totalSeconds}`);
    this.refreshLoadProgressDisplay(progress)
  }

  /** 加载进度条 */
  private refreshLoadProgressDisplay(percent: number) {
    if (percent > 100) {
      percent = 100
    }
    EventManager.Instance.emit(GAME_STATE_ENUM.ShowTipOrProgress, {
      tip: '加载中...',
      progress: percent / 100,
      updateImmediately: percent === 0,
    })
    // this.loadProLab.string = Math.floor(percent) + "%";
  }

  /**
   * 开始自有账号登录流程 点击按钮操作后续
   */
  public startOwnAccountLogin() {
    this.createNewPipeline()
    this.pipeline.steps = [
      // this.checkResUpdate,
      // this.ownAccountLogin,
      // this.ownAccountLoginCallBack,
      // this.frontLoginRequest,
      // this.loadNecessary,
      // this.fetchPlayerData,
      // this.accessGame,
      // this.switchScene,
    ]
    this.pipelineFlow()
  }
  private pipelineFlow(err?: string) {
    const step = this.pipeline?.index ?? -2
    console.log(`pipelineFlow step:${step} err:${err} steps:${this.pipeline?.steps?.length}`)

    this.pipeline?.flow(err)
  }
}
